package globals
{
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;
	import flash.utils.getTimer;
	
	import waveData.LoopData;

	public class Primitive
	{
		private var _sound:Sound;
		private var _soundTransform:SoundTransform;
		private var _parent:TrueLoop;
		private var _playing:Boolean = false;
		private var _soundChannels:Vector.<SoundChannel>;
		
		public function Primitive(sound:Sound, parent:TrueLoop)
		{
			_soundChannels = new Vector.<SoundChannel>();
			_parent = parent;
			if (_parent != null)
			{
				parent.addPrimitive(Primitive(this));
			}
			_sound = sound;
			_soundTransform = new SoundTransform();

			_parent.addEventListener(TrueLoop.START_PLAYING, play);
			_parent.addEventListener(TrueLoop.STOP_PLAYING, stop);
		}
		
		private function play(event:Event = null):void
		{
			for each (var s:SoundChannel in _soundChannels) {
				s.soundTransform = _soundTransform;
			}
			_soundTransform.volume = _parent.volume;
			if (_playing) {
				if (!_parent.oneShot) {
					return void;
				}
			}
			var _soundChannel:SoundChannel = _sound.play(0, 0, _soundTransform);
			_soundChannels.push(_soundChannel);
			_playing = true;
			
			if (_parent.oneShot)
			{
				_parent.removeEventListener(TrueLoop.STOP_PLAYING, stop);
				_soundChannel.addEventListener(Event.SOUND_COMPLETE, soundDone);
				function soundDone(e:Event):void
				{
					_parent.addEventListener(TrueLoop.STOP_PLAYING, stop);
				}
			}
		}
		
		private function stop(event:Event = null):void
		{
			if (!_playing) return void;
			for each (var s:SoundChannel in _soundChannels)
			{
				s.stop();
			}
			_playing = false;
		}
		
		private function dispatchSpectrum():void
		{
			
		}

		public function get isPlaying():Boolean
		{
			return _playing;
		}

		public function get sound():Sound
		{
			return _sound;
		}

		public function set sound(value:Sound):void
		{
			_sound = value;
		}

	}
}